

package org.koyabr.webx.demo.danmaku.web.user.module.action;

import static org.koyabr.webx.demo.danmaku.web.common.DanmakuConstant.*;

import javax.servlet.http.HttpSession;

import com.alibaba.citrus.service.form.CustomErrors;
import com.alibaba.citrus.service.requestcontext.parser.ParameterParser;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.FormField;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;
import com.alibaba.citrus.util.StringUtil;
import org.koyabr.webx.demo.danmaku.biz.UserManager;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.User;
import org.koyabr.webx.demo.danmaku.web.common.DanmakuUser;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginAction {
    @Autowired
    private UserManager userManager;

    public void doLogin(@FormGroup("login") User user,
                        @FormField(name = "loginError", group = "login") CustomErrors err, Navigator nav,
                        HttpSession session, ParameterParser params) throws Exception {
        user = userManager.login(user.getUsername(), user.getPassword());

        if (user != null) {
            // 在session中创建danmakuUser对象
            DanmakuUser danmakuUser = (DanmakuUser) session.getAttribute(DANMAKU_USER_SESSION_KEY);

            if (danmakuUser == null || danmakuUser.hasLoggedIn()) {
                danmakuUser = new DanmakuUser();
            }

            danmakuUser.upgrade(user.getUsername());

            session.setAttribute(DANMAKU_USER_SESSION_KEY, danmakuUser);

            // 跳转到return页面
            redirectToReturnPage(nav, params);
        } else {
            err.setMessage("invalidNameOrPassword");
        }
    }

    public void doLogout(HttpSession session, Navigator nav, ParameterParser params) throws Exception {
        // 清除session中的user
        session.removeAttribute(DANMAKU_USER_SESSION_KEY);

        // 跳转到return页面
        redirectToReturnPage(nav, params);
    }

    private void redirectToReturnPage(Navigator nav, ParameterParser params) {
        String returnURL = params.getString("return");

        if (StringUtil.isEmpty(returnURL)) {
            nav.redirectTo(LOGIN_RETURN_DEFAULT_LINK);
        } else {
            nav.redirectToLocation(returnURL);
        }
    }
}
